<?php

namespace App\Kuafu\Export\Service\ExportFactory;

use App\Kuafu\Export\Model\ExportDownloadModel;
use App\Kuafu\Shop\Enum\ShopCodeEnum;
use App\Kuafu\Statistics\Service\StatisticsService;
use App\Support\ExcelService;
use Illuminate\Support\Str;

/**
 * app-外卖菜品销售
 */
class ExportAppWmGoodsService extends BaseExportService
{
    private string $localPath;

    public function query(): self
    {
        $shopId  = (int)($this->params['shopId'] ?? 0);
        $startAt = date('Y-m-d H:i:s', $this->params['showStartAt'] ?? time());
        $endAt   = date('Y-m-d H:i:s', $this->params['showEndAt'] ?? time());
        $orderBy = 'createdAt';
        $byType  = 'desc';
        $source  = 2;

        $this->localPath = sys_get_temp_dir() . '/' . Str::random();

        self::streamExport($shopId, $startAt, $endAt, $this->localPath, $orderBy, $byType, $source);

        return $this;
    }

    public function path(): string
    {
        return $this->upload($this->localPath);
    }

    public static function streamExport(
        int $shopId,
        string $startAt,
        string $endAt,
        string $path,
        string $orderBy,
        string $byType,
        int $source
    ): array {

        list($dataArr, $fieldArr, $shopInfo) =
            (new ExcelService)->salesGoodsExcel($shopId, $startAt, $endAt, $orderBy, $byType, $source, false, 1);

        $data = self::getToChange($dataArr, $fieldArr, $shopInfo);

        // 生成excel
        $fileType = ExportDownloadModel::FILE_TYPE_APP_IN_GOODS;
        $client   = ExportDownloadModel::CLIENT_TYPE_APP;
        $fileName = (new ExportDownloadModel())->buildFileName($shopId, strtotime($startAt), strtotime($endAt),
            $fileType, $client);

        StatisticsService::spreadsheetExcel([[
            'info'  => $data['info'],
            'title' => $data['title'],
            'rows'  => iterator_to_array($data['rows']),// 把yield转成数组
        ]], $fileName, $path);

        return $data;
    }

    /**
     * 导出信息组装
     * @param $storeOrderList
     * @param $fieldArr
     * @param $shopInfo
     * @return array
     */
    public static function getToChange(
        $storeOrderList,
        $fieldArr,
        $shopInfo
    ): array {
        $rows = self::yieldOrderInfo($storeOrderList, $fieldArr);
        return [
            'title' => '外卖菜品销售',
            'info'  => [
                '门店'   => $shopInfo['name'],
                '门店编码' => str_pad($shopInfo['shopCode'],
                    ShopCodeEnum::CODE_TEXT[ShopCodeEnum::LEADING_ZERO], "0", STR_PAD_LEFT),//门店编号
            ],
            'rows'  => $rows
        ];
    }

    public static function yieldOrderInfo($orderList, $fieldArr): \Generator
    {
        $rows = $fieldArr;
        yield $rows;
        foreach ($orderList as $key => $value) {
            $rows[$key + 1] = [
                $value['productName'],
                $value['unit'],
                $value['sourceType'],
                $value['num'],
                $value['saleProportion'],
                $value['originalPrice'],
                $value['originalPriceProportion'],
                $value['payPrice'],
                $value['payProportion'],
                $value['discount'],
                $value['discountProportion'],
            ];
            yield $rows[$key + 1];
        }
    }
}
